import {
    colorUISdk
} from "../../config/mp-sdk";
import {updateCurrentPageShare} from "../../mp-sdk/lib/share";

const app = getApp();
let interstitialAd = null
Page({
    data: {
        marqueeText: '感谢车友们的鼎立支持,本公司郑重承诺：一次购买 永久使用！让车友们用的 安心、放心、省心！！！',
        marqueeDistance: 0,
        marqueeSpeed: 0.8,
        marqueeWidth: 0,
        windowWidth: 0,
        userInfo: {
            id: '',
            avatar: '',
            nickname: '',
            carQrcode: [],  // 确保初始化是数组
            wx_notice: 0,
            group_img: '',
            phone: '',
            backup_phone: '',
            is_privacy: 1,
            qrcode_url: '',
            is_bind: false,
            is_open_distribution: 0,
        },
        modal: {
            show: false,
            title: '',
            content: ""
        },
    },
    onLoad() {
        this.getUserInfo();
        const query = wx.createSelectorQuery();
        query.select('.coco-marquee-text').boundingClientRect();
        query.select('.coco-marquee-container').boundingClientRect();
        query.exec((res) => {
            if (res[0] && res[1]) {
                this.setData({
                    marqueeWidth: res[0].width,
                    windowWidth: res[1].width
                });
                this.startMarquee();
            }
        });
    },
    // 拉取用户及二维码列表
    getUserInfo() {
        colorUISdk.request({
            url: 'api/user/info',
            method: 'GET',
            data: {}
        }).then(res => {
            if (res && res.code === 1) {
                this.setUserInfo(res.data);
                // 登录成功后立即更新分享配置
                updateCurrentPageShare();
            } else {
                wx.showToast({title: res.msg || '获取失败', icon: 'none'});
            }
        }).catch(err => {
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    setUserInfo(data) {
        this.setData({
            userInfo: this.formatUserInfo(data)
        });
        app.userInfo = this.data.userInfo;
    },
    // 格式化接口返回数据，避免空值错误
    formatUserInfo(data) {
        return {
            id: data.id || '',
            avatar: data.avatar || '',
            nickname: data.nickname || '',
            carQrcode: Array.isArray(data.carQrcode) ? data.carQrcode : [],
            wx_notice: data.wx_notice || 0,
            group_img:data.group_img || '',
            phone: data.phone || '',
            backup_phone: data.backup_phone || '',
            is_privacy: data.is_privacy || 1,
            qrcode_url: data.qrcode_url || '',
            is_bind: data.is_bind || false,
            can_withdraw: data.can_withdraw || 0.00,
            pending_amount: data.pending_amount || 0.00,
            is_open_distribution: data.is_open_distribution || 0,
        };
    },
    onInputChange(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail.value;
        this.setData({[`userInfo.${field}`]: value});
    },

    onSwitchChange(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail ? 1 : 0;
        this.setData({[`userInfo.${field}`]: value});
    },
    goToGenerate() {
        colorUISdk.request({
            url: 'api/user/create_experience_qrcode',
            method: 'POST',
            data: {from: this.data.userInfo}
        }).then(res => {
            if (res.code === 1) {
                this.setUserInfo(res.data);
            } else {
                wx.showToast({title: res.msg, icon: 'none'});
            }
        }).catch(() => {
            wx.showToast({title: '系统异常', icon: 'none'});
        });

    },
    changeWxNotice(e) {
        if (e.detail) {
            this.subscribe();
        } else {
            colorUISdk.request({
                url: 'api/user/change_wx_notice',
                method: 'POST',
                data: {
                    wx_notice: 0
                }
            }).then(res => {
                if (res.code === 1) {
                    this.setUserInfo(res.data);
                    wx.showToast({title: res.msg, icon: 'success'});
                } else {
                    wx.showToast({title: res.msg, icon: 'none'});
                }
            });
        }
    },
    subscribe() {
        wx.requestSubscribeMessage({
            tmplIds: ['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'],
            success: res => {
                if (res['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'] === 'accept') {
                    colorUISdk.request({
                        url: 'api/user/change_wx_notice',
                        method: 'POST',
                        data: {wx_notice: 1}
                    }).then(res => {
                        if (res.code === 1) {
                            this.setUserInfo(res.data);

                            this.setData({
                                modal: {
                                    show: true,
                                    title: '订阅成功',
                                    content: res.msg
                                }
                            });
                        } else {
                            wx.showToast({title: res.msg, icon: 'none'});
                        }
                    });
                }
            }
        });
    },
    saveImage() {
        wx.downloadFile({
            url: this.data.userInfo.qrcode_url,
            success(res) {
                if (res.statusCode === 200) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: () => wx.showToast({title: '保存成功'}),
                        fail: () => wx.showToast({title: '保存失败', icon: 'none'})
                    });
                }
            }
        });
    },
    goToUnbind(){
        colorUISdk.request({
            url: 'api/user/unbind_experience_qrcode',
            method: 'POST',
            data: {}
        }).then(res => {
            if (res.code === 1) {
                this.setUserInfo(res.data);
                this.setData({
                    userInfo:{
                        phone:'',
                        backup_phone: '',
                        is_privacy: res.data.is_privacy,
                        wx_notice: res.data.wx_notice,
                    }
                });
            } else {
                wx.showToast({title: res.msg, icon: 'none'});
            }
        }).catch(() => {
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    startMarquee() {
        this._marqueeTimer = setInterval(() => {
            let distance = this.data.marqueeDistance + this.data.marqueeSpeed;
            if (distance >= this.data.marqueeWidth + this.data.windowWidth) {
                distance = 0;
            }
            this.setData({
                marqueeDistance: distance
            });
        }, 16);
    },

    onUnload() {
        if (this._marqueeTimer) {
            clearInterval(this._marqueeTimer);
        }
    }
})